import java.util.Random;
import java.util.Scanner;

public class Lab_01 {
    private static final Random random = new Random();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("=== 智能口算练习系统 ===");

        // 用户设置
        int questionCount = getQuestionCount();
        int maxNumber = getMaxNumber();
        boolean includeAddition = getOperationType("加法");
        boolean includeSubtraction = getOperationType("减法");

        // 生成题目
        String[] questions = generateCustomQuestions(questionCount, maxNumber,
                includeAddition, includeSubtraction);

        // 显示题目
        displayQuestions(questions);

        // 答题和批改
        takeQuiz(questions);

        scanner.close();
    }

    private static int getQuestionCount() {
        System.out.print("请输入题目数量(默认50): ");
        String input = scanner.nextLine();
        if (input.isEmpty()) return 50;
        try {
            return Integer.parseInt(input);
        } catch (NumberFormatException e) {
            return 50;
        }
    }

    private static int getMaxNumber() {
        System.out.print("请输入最大数字(默认100): ");
        String input = scanner.nextLine();
        if (input.isEmpty()) return 100;
        try {
            return Integer.parseInt(input);
        } catch (NumberFormatException e) {
            return 100;
        }
    }

    private static boolean getOperationType(String operation) {
        System.out.print("是否包含" + operation + "?(y/n, 默认y): ");
        String input = scanner.nextLine();
        return input.isEmpty() || input.equalsIgnoreCase("y");
    }

    private static String[] generateCustomQuestions(int count, int max,
                                                    boolean add, boolean sub) {
        String[] questions = new String[count];

        for (int i = 0; i < count; i++) {
            if (add && !sub) {
                questions[i] = generateAdditionQuestion(max);
            } else if (!add && sub) {
                questions[i] = generateSubtractionQuestion(max);
            } else {
                // 随机选择加法或减法
                if (random.nextBoolean()) {
                    questions[i] = generateAdditionQuestion(max);
                } else {
                    questions[i] = generateSubtractionQuestion(max);
                }
            }
        }

        return questions;
    }

    private static String generateAdditionQuestion(int max) {
        int num1, num2;
        do {
            num1 = random.nextInt(max) + 1;
            num2 = random.nextInt(max) + 1;
        } while (num1 + num2 > max);

        return String.format("%2d + %2d = ", num1, num2);
    }

    private static String generateSubtractionQuestion(int max) {
        int num1, num2;
        do {
            num1 = random.nextInt(max) + 1;
            num2 = random.nextInt(max) + 1;
        } while (num1 < num2);

        return String.format("%2d - %2d = ", num1, num2);
    }

    private static void displayQuestions(String[] questions) {
        System.out.println("\n=== 生成的题目 ===");
        for (int i = 0; i < questions.length; i++) {
            System.out.printf("第%2d题: %s", i + 1, questions[i]);
            if ((i + 1) % 5 == 0) System.out.println();
        }
    }

    private static void takeQuiz(String[] questions) {
        System.out.print("\n是否开始答题?(y/n): ");
        if (!scanner.nextLine().equalsIgnoreCase("y")) return;

        int correctCount = 0;
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < questions.length; i++) {
            System.out.printf("第%2d题: %s", i + 1, questions[i]);
            int userAnswer = getValidInput();

            int correctAnswer = calculateAnswer(questions[i]);

            if (userAnswer == correctAnswer) {
                System.out.println("  ✓ 正确");
                correctCount++;
            } else {
                System.out.printf("  ✗ 错误，正确答案: %d\n", correctAnswer);
            }
        }

        long endTime = System.currentTimeMillis();
        showResults(correctCount, questions.length, endTime - startTime);
    }

    private static int getValidInput() {
        while (true) {
            try {
                return Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.print("请输入有效的数字: ");
            }
        }
    }

    private static int calculateAnswer(String question) {
        String clean = question.replace(" ", "");
        if (clean.contains("+")) {
            String[] parts = clean.split("\\+");
            return Integer.parseInt(parts[0]) + Integer.parseInt(parts[1].split("=")[0]);
        } else {
            String[] parts = clean.split("-");
            return Integer.parseInt(parts[0]) - Integer.parseInt(parts[1].split("=")[0]);
        }
    }

    private static void showResults(int correct, int total, long timeMillis) {
        double score = (double) correct / total * 100;
        double timeSeconds = timeMillis / 1000.0;

        System.out.println("\n=== 答题结果 ===");
        System.out.printf("正确题数: %d/%d\n", correct, total);
        System.out.printf("得分: %.1f分\n", score);
        System.out.printf("用时: %.1f秒\n", timeSeconds);
        System.out.printf("平均每题: %.1f秒\n", timeSeconds / total);

        // 评价
        if (score == 100) System.out.println("🎉 完美！全对！");
        else if (score >= 90) System.out.println("👍 优秀！");
        else if (score >= 80) System.out.println("😊 良好！");
        else if (score >= 60) System.out.println("💪 及格，继续努力！");
        else System.out.println("📚 需要更多练习！");
    }
}